﻿$(function () {
    'use strict';
    $.ajax({
        type: "GET",
        url: "/PasteSheet/GetFiles/",
        //data: { username: $("#username").val(), content: $("#content").val() },
        dataType: "json",
        success: function (data) {
            var tbody = $('#tbodyFiles');
            $.each(data.files, function (index, file) {
                tbody.append(createTr(file));
            });
        }
    });
    function createTr(file) {
        var tr = $('<tr></tr>');
        //radio
        $('<td></td>').append($('<input type="radio" name="isMain"/>').prop('checked', file.isMain)).appendTo(tr);
        //link
        $('<td></td>').append($('<a href="#"></a>').text(file.name)).appendTo(tr);
        //button del
        $('<td></td>').append($('<button class="delBtn">Del</button>').prop('data-id', file.name)).appendTo(tr);
        return tr;
    }

    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            var tbody = $('#tbodyFiles');
            data.context = createTr(data.files[0]).appendTo(tbody);
            //check if first file set isMain
            //table find tr
            if ($('#tbodyFiles').find('tr').length == 1) {
                data.context.find('input[type=radio]').prop('checked', true);
            }
            data.submit();
        },
        progress: function (e, data) {
            var progress = parseInt((data.loaded / data.total) * 100, 10);
            data.context.css("background-position-x", 100 - progress + "%");
        },
        done: function (e, data) {
            data.context
                .addClass("done")
                .find("a")
                .prop("href", data.result.files[0].url);
        }
    });
    //delete file
    $(document).on('click', '.delBtn', function (e) {
        var tr = $(this).closest('tr');
        var flag = tr.find('input[type=radio]').prop('checked');
        tr.remove();

        if (flag!==undefined && flag === true) {
            $('input[type=radio]').first().prop('checked', true);
        }

        //server side
        //UI side
        //check if isMain checked
    })
    //setMain file
    $(document).on('change', 'input[type=radio]', function (e) {
        //$('input[type=radio]').prop("checked", false);
        //$(this).prop("checked", true);
        //var a = radio.closest('tr').find('a');
        //alert(a.prop('innerText'));
        //server side
    })
    /*  // Initialize the jQuery File Upload widget:
      $('#fileupload').fileupload({
          // Uncomment the following to send cross-domain cookies:
          //xhrFields: {withCredentials: true},
          url: '/PasteSheet/upload/',
          showElementClass: 'show',
          autoUpload:true
      });*/
});
